import sys
import signal

from motor.utils.logger import get_logger
from motor.node_manager.api_server.node_manager_api import NodeManagerAPI
from motor.config.node_manager import NodeManagerConfig
from motor.node_manager.core.daemon import Daemon
from motor.node_manager.core.engine_manager import EngineManager
from motor.node_manager.core.heartbeat_manager import HeartbeatManager

logger = get_logger(__name__)

modules = []

def stop_all_modules() -> None:
    for module in modules:
        if hasattr(module, 'stop'):
            module.stop()
    logger.info("All modules stoped.")

def signal_handler(sig, frame) -> None:
    logger.info(f"\nRecive signal {sig}，exit gracefully...")
    stop_all_modules()
    sys.exit(0)

def main() -> None:
    # Register signal handlers
    signal.signal(signal.SIGINT, signal_handler)  # Ctrl+C
    signal.signal(signal.SIGTERM, signal_handler)  # kill

    modules.append(NodeManagerConfig())
    modules.append(Daemon())
    modules.append(EngineManager())
    modules.append(HeartbeatManager())
    modules.append(NodeManagerAPI(
        host=NodeManagerConfig.pod_ip,
        port=NodeManagerConfig.node_manager_port,
    ))

    logger.info("All modules started, monitoring...")
    
    logger.info("Press Ctrl+C or type 'stop' to exit.")
    try:
        while True:
            try:
                user_input = input().strip().lower()
                if user_input == 'stop':
                    break
                elif user_input:
                    logger.warning(f"Unknow command: {user_input}")
            except EOFError:
                # In non-interactive environment, keep program running
                import time
                time.sleep(1)
    except KeyboardInterrupt:
        pass
    
if __name__ == '__main__':
    main()